﻿using IP2Region.Net.Abstractions;
using IP2Region.Net.XDB;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Polaris.Common
{
    public class IpHandler
    {
        /// <summary>
        /// 获取外网IP
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static async Task<string> GetExternalIPAddressAsync()
        {
            // 使用HttpClient版本（推荐，异步且更现代）
            using (var client = new HttpClient())
            {
                var response = await client.GetAsync("http://myip.ipip.net"); // 或者使用其他提供IP查询服务的网址
                if (response.IsSuccessStatusCode)
                {
                    string content = await response.Content.ReadAsStringAsync();
                    return Regex.Match(content, @"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}").Value;
                }
                else
                {
                    throw new Exception($"无法获取IP地址：HTTP状态码 {response.StatusCode}");
                }
            }
        }

        /// <summary>
        /// 获取IP所在地区
        /// </summary>
        /// <param name="ipAddress"></param>
        /// <returns></returns>
        public static string GetstringIpAddress(string ipAddress)
        {
            try
            {
                string html = GetHtml("https://www.ip138.com/iplookup.asp?ip=" + ipAddress + "&action=2", "gb2312");
                string pre = "var ip_result = ";
                int pos = html.IndexOf(pre);
                html = html.Substring(pos + pre.Length);
                html = html.Substring(0, html.IndexOf(';'));
                var json = JsonConvert.DeserializeObject<dynamic>(html);
                var ct = json.ip_c_list[0].ct;
                var prov = json.ip_c_list[0].prov;
                var city = json.ip_c_list[0].city;
                var area = json.ip_c_list[0].area;
                return $"{ct} {prov} {city} {area}";
                var a = json["ASN归属地"].ToString();
                string[] res = html.Split(new char[] { '省', '市', ' ' }, StringSplitOptions.RemoveEmptyEntries);
                return res[1];
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        /// <summary>
        /// 抓取网页查询信息
        /// </summary>
        /// <param name="url"></param>
        /// <param name="encoding">编码类型</param>
        /// <returns></returns>
        private static string GetHtml(string url, string encoding)
        {
            string pagehtml = string.Empty;
            try
            {
                using (WebClient MyWebClient = new WebClient())
                {
                    //控制台应用和.net core 需要这一句，需要安装NetGet包System.Text.Encoding.CodePages
                    Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                    Encoding encode = Encoding.GetEncoding(encoding);
                    MyWebClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36");
                    MyWebClient.Credentials = CredentialCache.DefaultCredentials;
                    Byte[] pageData = MyWebClient.DownloadData(url);
                    pagehtml = encode.GetString(pageData);
                }
            }
            catch (Exception ex)
            {

                return "访问" + url + "失败，请检查网络配置";
            }
            return pagehtml;
        }

        /// <summary>
        /// ip2region获取IP归属地
        /// </summary>
        /// <param name="ipAddres"></param>
        /// <returns></returns>
        public static string IpGetCity(string ipAddres)
        {
            try
            {
                //这里为啥直接填写ip2region.xdb，因为用了始终复制
                ISearcher searcher = new Searcher(CachePolicy.File, "ip2region.xdb");
                var ipResult = searcher.Search(ipAddres);

                return ipResult ?? "";
            }
            catch (WebException webEx)
            {
                return webEx.Message;
            }
        }
    }
}
